package com.example.seakdreamandroid;

import static com.example.seakdreamandroid.Constant.BASE_URL;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.seakdreamandroid.accountInfo.AccountInfoActivity;
import com.example.seakdreamandroid.bonus.BonusPointsActivity;
import com.example.seakdreamandroid.crosstalk.Audio;
import com.example.seakdreamandroid.crosstalk.GridViewMethod;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.lottery.Lottery;
import com.example.seakdreamandroid.myInfo.MyInfo;
import com.example.seakdreamandroid.playHistory.PlayHistoryActivity;
import com.example.seakdreamandroid.sleepRecord.SleepRecordActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MineActivity extends Fragment {
    private TextView nickname;
    private ImageView headshot;
    private TextView description;
    private View view;
    public User user;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.mine_activity, container, false);
        Button baogao = view.findViewById(R.id.baogao);
        Button record = view.findViewById(R.id.recordmonth);
        Button mylove = view.findViewById(R.id.mylove);
        Button myhistory = view.findViewById(R.id.myhistory);
        Button mypoints = view.findViewById(R.id.mypoints);

        Button lottery = view.findViewById(R.id.lottery);

        nickname = view.findViewById(R.id.my_nickname);
        headshot = view.findViewById(R.id.headshot);
        description = view.findViewById(R.id.description);
        user = (User)getContext().getApplicationContext();
        LinearLayout  myinfo = view.findViewById(R.id.myinfo);
        LinearLayout  members = view.findViewById(R.id.members);

        TextView openMember = view.findViewById(R.id.open_member);
        if (user.getIf_vip().equals("1")) {
            openMember.setText("续费寻梦vip");
        } else if (user.getIf_vip().equals("2")) {
            openMember.setText("开通寻梦vip");
        }

        setview();
        //跳转到会员充值界面 ---张清雅
        members.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),MemberActivity.class);
                startActivity(intent);
            }
        });
        myinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),AccountInfoActivity.class);
                startActivity(intent);
            }
        });
        baogao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SleepRecordActivity.class);
                startActivity(intent);
            }
        });
        record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SleepRecordActivity.class);
                intent.putExtra("page",2);
                startActivity(intent);
            }
        });
        mylove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),FavoriteActivity.class);
                startActivity(intent);
            }
        });
        myhistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), PlayHistoryActivity.class);
                startActivity(intent);

            }
        });
        mypoints.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), BonusPointsActivity.class);
                startActivity(intent);

            }
        });

        lottery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), Lottery.class);
                startActivity(intent);

            }
        });

        return view;
    }
    public void setview(){
        String userId = user.getUserId();
        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url(BASE_URL+"UserInfo/getUserInfo"+"?id="+userId)
                //创建Request对象
                .build();
        //3.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e("MineActivity","onFailure，请求数据失败");
                e.printStackTrace();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),"网络故障，请检查网络",Toast.LENGTH_LONG).show();

                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功时回调
                Log.i("MineActivity","onResponse"+"成功");
                try {
                    String resultStr = response.body().string();
                    JSONObject object = new JSONObject(resultStr);
                    JSONObject data = object.getJSONObject("data");
                    if(!data.isNull("headshot")){
                        String headshot1 = data.getString("headshot");
                        byte[] bs = Base64.decode(headshot1, Base64.DEFAULT);
                        for (int i = 0; i < bs.length; ++i) {
                            if (bs[i] < 0) {
                                bs[i] += 256;
                            }
                        }
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bs,0,bs.length);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Glide.with(getActivity()).load(bitmap).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(headshot);
                            }
                        });
                    }
                    if(!data.isNull("userName")){
                        String if_vip = data.getString("ifVip");
                        String nickname1 = data.getString("userName");
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (if_vip.equals("1")){
                                    nickname.setText(nickname1+"(会员)");
                                    nickname.setTextColor(Color.RED);
                                }else {
                                    nickname.setText(nickname1);
                                    nickname.setTextColor(Color.BLACK);
                                }

                            }
                        });
                    }
                    if(!data.isNull("description")){
                        String description1 = data.getString("description");
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                description.setText(description1);
                            }
                        });
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                //setview
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        setview();
    }

    /* private void getData(){

            OkHttpClient okHttpClient = new OkHttpClient()
                    .newBuilder().sslSocketFactory(getSSLSocketFactory(),trustManager).hostnameVerifier(getHostnameVerifier()).build();
            //2.创建请求体对象（FromBody）
            FormBody body = new FormBody.Builder()
                    .add("userName","逆天邪神")
                    .add("loginName","在线")
                    .add("password","卖")
                    .add("gender","8848")
                    .build();
            //3.创建请求对象（Request）
            Request request = new Request.Builder()
                    //设置
                    .url(BASE_URL)
                    .post(body)//设置请求方式为POST，添加了请求体
                    //创建Request对象
                    .build();
            //4.发送请求，获取响应
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("OkHttp","onFailure");
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.e("OkHttp","请求成功");
                    Log.e("响应码",response.code()+"");
                    Log.e("响应体",response.body().string());
                    Log.e("当前线程",Thread.currentThread().getName());
                    //修改用户界面，需要使用Handler或者runOnUiThread
                }
            });
        }*/
    final X509TrustManager trustManager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    };
    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }

    /**
     * description 忽略https证书验证
     *`在这里插入代码片`
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }




}
